package com.yangchoi.jetpackcompose.ui.widget.component

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.WindowManager
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.graphics.drawable.toBitmap
import coil.compose.rememberImagePainter
import coil.transform.RoundedCornersTransformation
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.rememberPagerState
import com.yangchoi.jetpackcompose.R

// 图片扩展文件

/**
 * 加载网络图片
 * @param imgUrl 图片地址
 * @param modifier
 * @param placeholderImage 占位图
 * @param errorImage 加载出错占位图
 */
@Composable
fun LoadNetWorkImage(
    imgUrl:String,
    modifier: Modifier,
    placeholderImage:Int = R.mipmap.ic_launcher,
    errorImage:Int = R.mipmap.ic_launcher
){
    Image(
        painter = rememberImagePainter(data = imgUrl, builder = {
            transformations(RoundedCornersTransformation())
            placeholder(placeholderImage)
            error(errorImage)
        }),
        contentDescription = "Network Image",
        modifier = modifier,
        contentScale = ContentScale.FillBounds
    )
}

/**
 * 加载本地图片
 * @param imgUrl 图片地址
 * @param modifier
 */
@Composable
fun LoadLocalImage(
    imgUrl: String,
    modifier: Modifier
){
    val drawable = Drawable.createFromPath(imgUrl)
    val bitmap = drawable?.toBitmap()?.asImageBitmap()
    Image(
        bitmap = bitmap!!,
        contentDescription = null,
        modifier = modifier,
        contentScale = ContentScale.FillBounds
    )
}


/**
 * 查看大图 ==============================================start==========================================
 */
class FullscreenImageActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        window.statusBarColor = android.graphics.Color.BLACK
        window.navigationBarColor = android.graphics.Color.TRANSPARENT
        window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)

        val position = intent.getIntExtra("position", 0)
        val imageUrls = intent.getStringArrayExtra("imageUrls") ?: emptyArray()

        setContent {
            FullscreenImage(
                imageUrl = imageUrls[position],
                onDismiss = {
                    this@FullscreenImageActivity.finish()
                },
                modifier = Modifier
                    .fillMaxSize()
                    .background(color = Color(0xff000000)),
                images = imageUrls.toList()
            )
        }
    }
}

@OptIn(ExperimentalPagerApi::class)
@Composable
fun FullscreenImage(
    imageUrl: String,
    onDismiss: () -> Unit,
    modifier: Modifier = Modifier,
    images: List<String>
) {
    val pagerState = rememberPagerState(initialPage = images.indexOf(imageUrl))

    Box(modifier = modifier) {
        HorizontalPager(count = images.size, state = pagerState) {
            Box(modifier = Modifier
                .fillMaxSize()
                .clickable { onDismiss() }){
                Text(text = "${it + 1} / ${images.size}", style = TextStyle(color = androidx.compose.ui.graphics.Color.White, fontSize = 16.sp), modifier = Modifier
                    .padding(top = 10.dp)
                    .align(
                        Alignment.TopCenter
                    ))
                ZoomableImage(imageUrl = imageUrl)

            }
        }
    }
}

@Composable
fun ZoomableImage(
    imageUrl: String,
    maxScale: Float = 4f,
    minScale: Float = 0.5f,
) {
    var scale by remember { mutableStateOf(1f) }
    var offset by remember { mutableStateOf(Offset.Zero) }

    Image(
        painter = rememberImagePainter(data = imageUrl, builder = {
            transformations(RoundedCornersTransformation())
            placeholder(R.mipmap.ic_launcher) // 占位图片，
            error(R.mipmap.ic_launcher) // 加载错误图片
        }),
        contentDescription = null,
        modifier = Modifier
            .fillMaxSize()
            .graphicsLayer(
                scaleX = scale,
                scaleY = scale,
                translationX = offset.x,
                translationY = offset.y
            )
            .pointerInput(Unit) {
                detectTransformGestures { _, pan, zoom, _ ->
                    // 缩放范围限制
                    val newScale = (scale * zoom).coerceIn(minScale, maxScale)

                    // 计算缩放后的偏移量
                    val pivot = (pan - offset) / scale
                    val newOffset = pan - pivot * newScale

                    // 更新缩放和偏移量
                    scale = newScale
                    offset = newOffset
                }
            }
    )
}
/**
 * 查看大图 ==============================================end==========================================
 */